package com.youzhi.backend.service.impl;

import com.youzhi.backend.dto.OperateLogTypeEnum;
import com.youzhi.backend.entity.OperateLog;
import com.youzhi.backend.mapper.OperateLogMapper;
import com.youzhi.backend.service.IOperateLogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youzhi.backend.service.IUserSessionService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * 系统操作日志 服务实现类
 * </p>
 *
 * @author xumeng
 * @since 2022-12-10
 */
@Service
@Slf4j
public class OperateLogServiceImpl extends ServiceImpl<OperateLogMapper, OperateLog> implements IOperateLogService {


    @Autowired
    private IUserSessionService userSessionService;

    @Override
    public void addOperateLog(OperateLogTypeEnum type, String desc, String dataId) {

        String currentUser = userSessionService.getCurrentUser();

        try {
            OperateLog operateLog = new OperateLog();
            operateLog.setUserName(currentUser);
            long userId = Long.parseLong(userSessionService.getCurrentUserAttr(IUserSessionService.attr_userId).toString());
            operateLog.setUserId(userId);
            operateLog.setOperateType(type.code);
            operateLog.setDescription(desc);
            operateLog.setDataId(dataId);
            String clientIp = userSessionService.getCurrentUserAttr(IUserSessionService.attr_clientIp).toString();
            operateLog.setClientIp(clientIp);
            operateLog.setCreateTime(new Date());
            operateLog.setUpdateTime(new Date());
            save(operateLog);
        } catch (Exception e) {
            log.error("操作日志保存失败user={},type={},desc={},dataId={}", currentUser, type.desc, desc, dataId);
        }

    }
}
